﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using LINQPad.OpenAccess.Helpers;
using LINQPad.OpenAccess.Settings;

namespace LINQPad.OpenAccess.Services
{
    /// <summary>
    /// <see cref="IConnectionStringBuilderFactory"/>
    /// </summary>
    public class ConnectionStringBuilderFactory : IConnectionStringBuilderFactory
    {
        #region Private

        #region - Vars

        [DebuggerBrowsable( DebuggerBrowsableState.Never )]
        private readonly IConnectionStringBuilder[] _connectionStringBuilders;

        #endregion

        #endregion

        #region Public

        #region - Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionStringBuilderFactory" /> class.
        /// </summary>
        /// <param name="connectionStringBuilders">The connection string builders.</param>
        public ConnectionStringBuilderFactory( IEnumerable<IConnectionStringBuilder> connectionStringBuilders )
        {
            Guard.ArgumentNotNull( connectionStringBuilders, "connectionStringBuilders" );
            this._connectionStringBuilders = connectionStringBuilders.ToArray( );
        }

        #endregion

        #endregion

        #region IConnectionStringBuilderFactory Members

        /// <summary>
        /// Creates the connection string builder for the specified parameters.
        /// </summary>
        /// <param name="providerName">Name of the provider.</param>
        /// <param name="connectionSettings">The connection settings.</param>
        /// <returns>
        /// The connection string builder or <c>null</c>.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IConnectionStringBuilder CreateConnectionStringBuilder( string providerName, ConnectionSettings connectionSettings = null )
        {
            return this._connectionStringBuilders
                       .Where( b => b.CanBuildConnectionStringFor( providerName, connectionSettings ) )
                       .FirstOrDefault( );
        }

        #endregion
    }
}
